package org.webdb.jdbc;

import java.util.List;

import javax.sql.DataSource;

import org.webdb.core.Document;
import org.webdb.core.config.DatabaseConfig;
import org.webdb.core.database.DataBase;

public class JDBCDataBase implements DataBase {

    private DataSource dataSource;
    private JDBCFactory factory;
    private JDBCMetaData meta;
    private String name;
    private DatabaseConfig config;

    public JDBCDataBase(String name, DataSource ds,
            DatabaseConfig databaseConfig) {
        this.name = name;
        this.dataSource = ds;
        this.config = databaseConfig;
    }

    public Document getDocument(String clusterName, String documentName) {
        JDBCTable table = getMeta().getTable(clusterName, documentName);
        if (table == null) {
            throw new JDBCException(toString() + " Table " + clusterName + ":"
                    + documentName + " doesn't exist!");
        }

        return new JDBCDocument(table, getFactory().getSqlProvider(),
                getFactory().getJDBCProvider());
    }

    public List<Document> getDocuments() {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException();
    }

    private JDBCFactory getFactory() {
        if (factory == null) {
            synchronized (this) {
                if (factory == null) {
                    factory = new JDBCFactory(getMeta(), dataSource);
                }
            }
        }
        return factory;
    }

    private JDBCMetaData getMeta() {
        if (meta == null)
            synchronized (this) {
                if (meta == null) {
                    try {
                        meta = new JDBCMetaData(getName(), dataSource,
                                new JDBCTreeTableStore(), config);
                    } catch (Exception e) {
                        throw new JDBCException(toString()
                                + " Creating Database Metadata!", e);
                    }
                }
            }

        return meta;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return JDBCDataBase.class.getSimpleName() + "[" + getName() + "]";
    }

}
